﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.EntityClient;
using System.Data.Objects;
using System.Configuration;

namespace EFMassOperations
{
	class EFConnectionStringParser
	{
		static Cache<ObjectContext, string, EntityConnectionStringBuilder> csParserCache =
			new Cache<ObjectContext, string, EntityConnectionStringBuilder>(
				(context) => context.Connection.ConnectionString,
				(context, connectionString) => ParseConnectionString(context));

		public static EntityConnectionStringBuilder GetConnectionStringParserCache(ObjectContext context)
		{
			return csParserCache[context];
		}

		static EntityConnectionStringBuilder ParseConnectionString(ObjectContext context)
		{
			string connectionString = context.Connection.ConnectionString;
			if (!connectionString.StartsWith("name="))
				throw new InvalidOperationException("ObjectContext.ConnectionString property has invalid format");
			string csName = connectionString.Substring("name=".Length);
			ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings[csName];
			EntityConnectionStringBuilder parser = new EntityConnectionStringBuilder(settings.ConnectionString);
			return parser;
		}
	}
}
